from django.shortcuts import get_object_or_404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from artmarket.models import Artwork, Order
from django.db import transaction

from artmarket.permissions.order_permission import IsBuyerOrArtist
from artmarket.serializers import OrderSerializer, OrderCreateSerializer
from users.models import CustomUser


class OrderListView(APIView):
    permission_classes = [IsBuyerOrArtist]

    def get(self, request):
        # 获取当前登录用户
        user = request.user

        # 根据用户角色查询订单
        if user.role == CustomUser.BUYER:
            # 如果用户是买家，获取买家创建的订单
            user_orders = Order.objects.filter(buyer=user)
        elif user.role == CustomUser.ARTIST:
            # 如果用户是艺术家，获取艺术家的艺术品对应的订单
            artist_artworks = Artwork.objects.filter(artist=user)
            user_orders = Order.objects.filter(artwork__in=artist_artworks)
        else:
            # 其他角色无权限查看订单
            return Response({'message': '用户角色无权限查看订单'}, status=status.HTTP_403_FORBIDDEN)

        serializer = OrderSerializer(user_orders, many=True)
        return Response(data={
            'results': serializer.data
        }, status=status.HTTP_200_OK)

    @transaction.atomic
    def post(self, request):
        # 创建订单
        serializer = OrderCreateSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save(buyer=request.user)
            return Response(data={
                'results': serializer.data
            }, status=status.HTTP_200_OK)
        return Response(data={
            'results': serializer.errors
        }, status=status.HTTP_400_BAD_REQUEST)


class OrderDetailView(APIView):
    def get(self, request, pk):
        objects_all = Order.objects.get(pk=pk)
        serializer = OrderSerializer(instance=objects_all)
        return Response(data={
            'results': serializer.data
        }, status=status.HTTP_200_OK)

    # def put(self, request, pk):
    #     pass
    def put(self, request, pk):
        user = request.user
        order = get_object_or_404(Order, pk=pk)

        # 检查订单是否属于当前用户且订单状态为已完成
        if order.buyer != user or order.status != Order.ORDER_COMPLETED:
            return Response({'error': '无法提交退货申请'}, status=status.HTTP_400_BAD_REQUEST)

        # 更新订单状态为退货申请中
        order.status = Order.ORDER_RETURN_REQUESTED
        order.save()

        return Response({'message': '退货申请已提交'}, status=status.HTTP_200_OK)

    def delete(self, request, pk):
        # 删除订单
        try:
            order = Order.objects.get(pk=pk)
            order.delete()
            return Response(data={'results': '订单删除成功'}, status=status.HTTP_200_OK)
        except Order.DoesNotExist:
            return Response(data={'results': '订单不存在'}, status=status.HTTP_400_BAD_REQUEST)

